package cn.com.dashihui.web.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.kit.ListKit;
import cn.com.dashihui.web.dao.Order;
import cn.com.dashihui.web.dao.OrderRefund;

public class OrderRefundService {

	/**
	 * 分页查找订单信息
	 * @param refundNum 退款单编号
	 * @param orderNum 订单编号
	 * @param beginDate 退款申请时间
	 * @param endDate 退款申请时间
	 * @param state 退款状态，1：待处理，2：审核中，3：审核通过，4：审核不通过
	 */
	public Page<Record> findByPage(int pageNum,int pageSize,String refundNum,String orderNum,String beginDate,String endDate,int state){
		StringBuffer sBuffer = new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		sBuffer.append("FROM t_bus_order_refund A INNER JOIN t_bus_order B ON A.orderNum=B.orderNum WHERE B.isSelf=1");
		if(!StrKit.isBlank(refundNum)){
			sBuffer.append(" AND A.refundNum=?");
			params.add(orderNum);
		}
		if(!StrKit.isBlank(orderNum)){
			sBuffer.append(" AND A.orderNum=?");
			params.add(orderNum);
		}
		if(!StrKit.isBlank(beginDate)&&!StrKit.isBlank(endDate)){
			sBuffer.append(" AND A.createDate BETWEEN ? AND ?");
			params.add(beginDate);
			params.add(endDate);
		}else if(!StrKit.isBlank(beginDate)&&StrKit.isBlank(endDate)){
			sBuffer.append(" AND DATE_FORMAT(A.createDate,'%Y-%m-%d')>=?");
			params.add(beginDate);
		}else if(StrKit.isBlank(beginDate)&&!StrKit.isBlank(endDate)){
			sBuffer.append(" AND DATE_FORMAT(A.createDate,'%Y-%m-%d')<=?");
			params.add(endDate);
		}
		if(state!=0){
			sBuffer.append(" AND A.state=?");
			params.add(state);
		}
		sBuffer.append(" ORDER BY createDate DESC");
		//查询出符合条件的订单列表
		Page<Record> page = Db.paginate(pageNum,pageSize,"SELECT A.*,B.amount orderAmount,B.payMethod ",sBuffer.toString(),params.toArray());
		if(page.getList()!=null&&page.getList().size()!=0){
			//将各订单对应的订单商品查出
			return new Page<Record>(findGoodsListByOrder(page.getList()), page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow());
		}
		return page;
	}
	
	/**
	 * 根据订单号查询出订单
	 */
	public OrderRefund getOrderRefundByOrderNum(String refundNum){
		String sql = "SELECT A.*,B.amount orderAmount,B.payMethod FROM t_bus_order_refund A INNER JOIN t_bus_order B ON A.orderNum=B.orderNum WHERE A.refundNum=?";
		return OrderRefund.me().findFirst(sql, refundNum);
	}
	
	/**
	 * 为指定订单列表，查找出相应的商品清单并set给每个订单记录
	 * @param orderList
	 */
	private List<Record> findGoodsListByOrder(List<Record> orderRefundList){
		//拼接SQL
		StringBuffer sBuffer = new StringBuffer("SELECT orderNum,thumb,name,price,count,amount FROM t_bus_order_list WHERE orderNum IN (");
		for(Record order : orderRefundList){
			sBuffer.append("'").append(order.getStr("orderNum")).append("',");
		}
		sBuffer.replace(sBuffer.lastIndexOf(","), sBuffer.length(), ")");
		sBuffer.append(" ORDER BY orderNum");
		//整理结果
		List<Record> goodsList = Db.find(sBuffer.toString());
		if(goodsList!=null){
			//先将查出来的所有的订单商品，按订单号归类
			Map<String,List<Record>> goodsMap = new HashMap<String,List<Record>>();
			for(Record goods : goodsList){
				if(goodsMap.containsKey(goods.getStr("orderNum"))){
					goodsMap.get(goods.getStr("orderNum")).add(goods);
				}else{
					goodsMap.put(goods.getStr("orderNum"), new ListKit<Record>().add(goods).getList());
				}
			}
			//遍历订单列表的同时，设置对应订单商品集
			for(Record order : orderRefundList){
				order.set("goodsList", goodsMap.get(order.get("orderNum")));
			}
		}
		return orderRefundList;
	}
	
	/**
	 * 根据订单号查询出原订单信息
	 */
	public Order getOrderByOrderNum(String orderNum){
		String sql = "SELECT * FROM t_bus_order WHERE orderNum=?";
		return Order.me().findFirst(sql,orderNum);
	}

	/**
	 * 根据订单号查询出原订单商品清单
	 */
	public List<Record> getGoodsListByOrderNum(String orderNum){
		String sql = "SELECT A.orderNum,A.goodsid,A.name as title,A.price,A.count,A.amount,B.name FROM t_bus_order_list A left join t_bus_goods B on A.goodsid = B.id WHERE A.orderNum=?";
		return Db.find(sql, orderNum);
	}
	
	/**
	 * 记录退款操作日志
	 */
	public void log(String refundNum,String orderNum, int type, String user, String action, String content){
		Db.update("INSERT INTO t_bus_order_log(orderNum,type,user,action,content) VALUES(?,?,?,?,?)",orderNum,type,user,action,content);
	}
}
